--
-- Author: shunguo.chen
-- Date: 2018-03-07 16:46:25
--
-- ChessView

local AvatarFactory = app:getClass("AvatarFactory")
local Armature = app:getClass("Armature")

local TabsBtn = require("app.widget.TabsBtn")
local ChessActionTipRender = import(".renders.ChessActionTipRender")
local ChessMiniPanel = import(".ChessMiniPanel")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.ChessScene

local REMAIN_TIME_STR = L("lua_code_text_352")
local ENEMY_ROUND_STR = L("lua_code_text_284")
local WAIT_START_STR = L("lua_code_text_456")

local TIP_MOVE_GAP = 42

function ClassRef:init()
	-- top
	self._ui["top/btn_esc"]:addClickEventListener(function()
			executeFunc(self._onOperate, "escape")
		end)
	-- self._ui["top/btn_set"]:addClickEventListener(function()
	-- 		executeFunc(self._onOperate, "openSet")
	-- 	end)
	self._ui["top/btn_auto"]:addClickEventListener(function()
			self:_switchMiniPanel()
		end)
	self._totalTimeText = self._ui["top/clock/time"]
	self._myScoreText = self._ui["top/score_1"]
	self._enemyScoreText = self._ui["top/score_2"]

	-- tips
	self._tipDataCaches = {}
	self._tips = {}
	self._idleTips = {0,0,0,0}
	self._idleTipPosY = 0
	self._isInTipAct = false
	for i=1,4 do
		local node = self._ui["tips_" .. (i-1)]
		local render = ChessActionTipRender.create()
		render:setPosition(node:getPosition())
		render:setOpacity(0)
		self._root:addChild(render, 1)
		self._idleTips[i] = render
		if i == 1 then
			self._idleTipPosY = node:getPositionY()
		end
		node:removeFromParent()
	end

	-- bom
	local bom = self._ui.bom
	bom:setLocalZOrder(2)
	bom:getChildByName("btn_reday"):addClickEventListener(function()
			executeFunc(self._onOperate, "openReady")
		end)

	self._rollTimeText = bom:getChildByName("time")
	self._rollTimeBg = bom:getChildByName("bg_time")

	self._randomBtn = bom:getChildByName("btn_random")
	self._randomBtn:addClickEventListener(function()
			executeFunc(self._onOperate, "roll")
		end)

	self._randomBtn:getChildByName("img"):setLocalZOrder(1)
	self._randomBtn:getChildByName("numbg"):setLocalZOrder(1)
	self._randomNumText = self._randomBtn:getChildByName("Text_num")
	self._randomNumText:setLocalZOrder(1)

	local sprite = self._randomBtn:getChildByName("Sprite")
	local pgSprite = cc.ProgressTimer:create(sprite)
	pgSprite:setPosition(sprite:getPosition())
	sprite:removeFromParent()
	self._randomBtn:addChild(pgSprite)
	self._randomSprite = pgSprite

	local btnPanel = bom:getChildByName("Panel_btn")
	display.nodeRemoveForNotHit(btnPanel, function() 
			if btnPanel:isVisible() then
				btnPanel:setVisible(false)
			end
		end)
	for i=1,6 do
		btnPanel:getChildByName("btn_" .. i):addClickEventListener(function()
				executeFunc(self._onOperate, "rollGold", i)
				btnPanel:setVisible(false)
			end)
	end
	btnPanel:setVisible(false)

	self._goldBtn = bom:getChildByName("btn_gold")
	self._goldNumText = self._goldBtn:getChildByName("Text_num")
	self._goldSprite = self._goldBtn:getChildByName("Sprite")
	self._goldBtn:addClickEventListener(function()
			btnPanel:setVisible(true)
			self:playAction("in")
		end)

	self._goldBtn:getChildByName("img"):setLocalZOrder(1)
	self._goldBtn:getChildByName("numbg"):setLocalZOrder(1)
	self._goldNumText = self._goldBtn:getChildByName("Text_num")
	self._goldNumText:setLocalZOrder(1)

	local sprite = self._goldBtn:getChildByName("Sprite")
	local pgSprite = cc.ProgressTimer:create(sprite)
	pgSprite:setPosition(sprite:getPosition())
	sprite:removeFromParent()
	self._goldBtn:addChild(pgSprite)
	self._goldSprite = pgSprite

	display.setCascadeOpacityEnabled(self._goldBtn, true)
	display.setCascadeOpacityEnabled(self._randomBtn, true)

	self:_createTouchLayer()
end

function ClassRef:show(index)
	self:setVisible(true)
end

function ClassRef:_createTouchLayer()
	local layer = ccui.Layout:create()
	layer:setContentSize(display.size)
	layer:setTouchEnabled(true)
	layer:setSwallowTouches(true)

	layer:setBackGroundColor(display.COLOR_BLACK)
	layer:setBackGroundColorOpacity(70)
	layer:setBackGroundColorType(1)

	layer:setVisible(false)
	self:addChild(layer, 9)
	self._touchLayer = layer
end

-- 切换小地图的显示
function ClassRef:_switchMiniPanel(forceShow)
	local isShow
	if not self._miniPanel then
		local panel = ChessMiniPanel.create()
		panel:setPosition(self._ui.minimap:getPosition())
		self._root:addChild(panel)
		self._miniPanel = panel
		isShow = true
	else
		isShow = forceShow or not self._miniPanel:isVisible()
	end

	if isShow then
		self._miniPanel:setData(self._info)
		self._miniPanel:show()
	else
		self._miniPanel:hide()
	end
end

function ClassRef:isMiniVisible()
	return self._miniPanel and self._miniPanel:isVisible()
end

-- info = ChessInfo
function ClassRef:refresh(info)
	self._info = info

	local myPlayer = info.myPlayer
	local enemyPlayer = info.enemyPlayer
	self._totalTimeText:setString(TimeUtil.secondsToTime(myPlayer:getTotalRemainTime()))
	self._myScoreText:setString(myPlayer.pos)
	self._enemyScoreText:setString(enemyPlayer.pos)

	self._goldNumText:setString(myPlayer.goldeDiceNUm)
	self._randomNumText:setString(myPlayer.normalDiceNum)

	self:roundChange()
	self:statusUpdate()

	self:_switchMiniPanel(true)
end

function ClassRef:roundChange()
	if self:isMiniVisible() then
		self._miniPanel:roundChange()
	end

end

function ClassRef:statusUpdate()
	-- print("statusUpdate")
	-- print("info.remainTime", self._info.remainTime)
	-- print("info.roundID", self._info.roundID)
	-- print("info.roundUID", self._info.roundUID)
	-- print("info.status", self._info.status)
	-- print("info.isMyRound", self._info:isMyRound())
	-- print("info.isNormalRollAble", self._info:isNormalRollAble())
	-- print("info.isGoldRollAble", self._info:isGoldRollAble())

	local info = self._info
	local myPlayer = info.myPlayer

	self._randomBtn:setTouchEnabled(info:isNormalRollAble())
	self._goldBtn:setTouchEnabled(info:isGoldRollAble())

	-- 停止动画
	self._randomBtn:stopAllActions()
	self._goldSprite:stopAllActions()
	self._randomSprite:stopAllActions()

	local showTip = true
	local tipMsg = nil
	local touchAble = false

	if info:isStart() then
		local isMyRound = info:isMyRound()
		if isMyRound then
			if info:isDice() then
				touchAble = true
			else
				showTip = false
			end
		else
			tipMsg = ENEMY_ROUND_STR
		end
	else
		tipMsg = WAIT_START_STR
	end

	self._rollTimeText:setVisible(showTip)
	self._rollTimeBg:setVisible(showTip)
	if showTip and tipMsg then
		self._rollTimeText:setString(tipMsg)
	end

	self._goldBtn:setOpacity(touchAble and 255 or 127)
	self._randomBtn:setOpacity(touchAble and 255 or 127)

	if touchAble then
		-- 可点击必然有倒计时和动画
		self:_refreshTime()

		local act = cca.progressFromTo(info:getRemainTime(), 100, 0)
		self._goldSprite:runAction(act)
		self._randomSprite:runAction(act:clone())
	else
		self._goldSprite:setPercentage(0)
		self._randomSprite:setPercentage(0)
	end
end

function ClassRef:_refreshTime()
	local info = self._info
	local remainTime = info:getRemainTime()

	if remainTime <= 0 then
		self._rollTimeText:setVisible(false)
		self._rollTimeBg:setVisible(false)
		return
	end

	local myPlayer = info.myPlayer
	local totalTime = myPlayer:getTotalRemainTime()

	self._totalTimeText:setString(TimeUtil.secondsToTime(totalTime))
	self._rollTimeText:setString(string.format(L(REMAIN_TIME_STR), remainTime))

	self._randomBtn:performWithDelay(function()
			self:_refreshTime()
		end, 1)
end

function ClassRef:_refreshTips()
	if self._isInTipAct then return end

	local tipsLen = #self._tips
	local cacheLen = #self._tipDataCaches
	if (tipsLen + cacheLen) == 0 then return end

	if tipsLen > 0 then
		for i,tip in ipairs(self._tips) do
			tip:playMove(i-1)
		end
		local removeTip = table.remove(self._tips, 1)
		table.insert(self._idleTips, removeTip)
	end

	if cacheLen > 0 then
		local sIdx = tipsLen > 0 and tipsLen or 1
		for i=sIdx,3 do
			if #self._tipDataCaches > 0 then
				local data = table.remove(self._tipDataCaches, 1)
				local tip = table.remove(self._idleTips, 1)
				tip:setData(data)
				tip:setPositionY(self._idleTipPosY + (3-i)*TIP_MOVE_GAP)
				tip:playMove(-1)
				table.insert(self._tips, tip)
			else
				break
			end
		end
	end

	self._isInTipAct = true
	self:performWithDelay(function()
			self._isInTipAct = false
			self:_refreshTips()
		end, 1)
end

function ClassRef:addActionTip(data)
	self._tipDataCaches[#self._tipDataCaches + 1] = data
	self:_refreshTips()
end

function ClassRef:refreshMyInfo(tp)
	local info = self._info
	local myPlayer = self._info.myPlayer

	-- print("info.isNormalRollAble", self._info:isNormalRollAble())
	-- print("info.isGoldRollAble", self._info:isGoldRollAble())
	-- dump(myPlayer, "refreshMyInfo.myPlayer")

	if tp == "NORMDICEDATA" then
		self._randomNumText:setString(myPlayer.normalDiceNum)
		self._randomBtn:setTouchEnabled(info:isNormalRollAble())
	elseif tp == "GOLDENDICEDATA" then
		self._goldNumText:setString(myPlayer.goldeDiceNUm)
		self._goldBtn:setTouchEnabled(info:isGoldRollAble())
	elseif tp == "REMAINTIMEDATA" then
		self._totalTimeText:setString(TimeUtil.secondsToTime(myPlayer:getTotalRemainTime()))
	end
end

function ClassRef:_getDiceArmature(tp)
	if not self["_diceArmature" .. tp] then
		local fileName = "dice" .. tp
		local params = {
			armatureName = fileName,
			path = string.format(Res.ChessRollEfcPath, fileName)
		}
		local armature = Armature.create(params)
		armature:setPosition(display.cx, display.cy - 80)
		self:addChild(armature, 10)
		self["_diceArmature" .. tp] = armature
	end
	return self["_diceArmature" .. tp]
end

function ClassRef:_playRollInEfc()
	if not self._inArmature then
		local params = {
			armatureName = "shaizibengchu",
			path = Res.ChessRollInEfcPath
		}
		local armature = Armature.create(params)
		armature:setPosition(display.cx, display.cy - 80)
		self:addChild(armature, 11)
		self._inArmature = armature
	end

	self._inArmature:setVisible(true)
	self._inArmature:play("shaizibengchu", 1, function(sender)
			sender:setVisible(false)
		end)
end

function ClassRef:playRollAction(num, tp)
	-- 显示屏蔽界面点击
	self._touchLayer:setVisible(true)

	local armature = self:_getDiceArmature(tp)
	armature:setVisible(true)

	local function playSecondAni()
		armature:play(tostring(num), 1, function(sender, name)
				sender:setVisible(false)
				self._touchLayer:setVisible(false)
				if self._info:isMyAction() or self._info:isRobotAction() then
					executeFunc(self._onOperate, "actionOver", "DiceAnim")
				end
			end)
	end

	armature:play("0", 1, function(sender, name)
			self:_playRollInEfc()
			self:performWithDelay(playSecondAni, 0)
		end)
end

function ClassRef:playerMove(startPos)
	if self:isMiniVisible() then
		self._miniPanel:playerMove(startPos)
	end

	-- 刷新位置
	self._myScoreText:setString(self._info.myPlayer.pos)
	self._enemyScoreText:setString(self._info.enemyPlayer.pos)
end

return ClassRef